package com.yangcangclub.trade.task;

import com.yangcangclub.commons.config.SysConfig;
import com.yangcangclub.commons.utils.DateUtil;
import com.yangcangclub.trade.bean.TradeSummary;
import com.yangcangclub.trade.domain.TradeDomain;
import com.yangcangclub.trade.service.TradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class TradeTask {
    private static Logger logger = LoggerFactory.getLogger(TradeTask.class);


    @Autowired
    private SysConfig sysConfig;
    
    @Autowired
    private TradeService tradeService;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @Scheduled(fixedDelay =60*1000)//上次任务结束后一分钟执行下一次
    public void  cancelPayTimeOutTrades() {
        /**↓↓↓↓↓↓↓↓↓↓分布式锁↓↓↓↓↓↓↓↓↓↓↓↓**/
        //启动开关，可根据环境调整是否开启
        if( !sysConfig.isTaskSwitch()){
            return;
        }
        boolean flag=false;
        int expireSeconds=1*60;//根据定时任务执行周期和时间调整,下面的键名也是
        BoundValueOperations bvo=redisTemplate.boundValueOps("trade.task.cancelpaytimeouttrades.sync");
        //判断是否有机器在执行该任务,占用了锁
        if( bvo.setIfAbsent(System.currentTimeMillis())) {
            bvo.expire(expireSeconds, TimeUnit.SECONDS);
            flag=true;
        }else{
            //检查值，避免有线程设置过期时间失败。
            long time=bvo.getExpire();
            if(time<0){
                bvo.expire(expireSeconds, TimeUnit.SECONDS);
            }
        }
        if( !flag ) return;//抢锁失败。
        /**↑↑↑↑↑↑↑↑↑↑↑分布式锁↑↑↑↑↑↑↑↑↑↑↑**/
        //下面写业务逻辑
        logger.info("订单超时关闭处理定时任务开始当前时间："+ DateUtil.getNowDate());
        List<TradeSummary> list=tradeService.selectPayTimeOutTrades(-30);
        if(list==null||list.size()==0){return ;}
        for(TradeSummary trade:list){//循环处理
            tradeService.cancelPayTimeOutTrades(trade.getId(),trade.getTradeNo());
        }
    }


}
